package com.taoyige.adapter;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.BitmapFactory;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.taoyige.AppConfig;
import com.taoyige.AppContext;
import com.taoyige.AppException;
import com.taoyige.R;
import com.taoyige.bean.AlipayResult;
import com.taoyige.bean.Order;
import com.taoyige.bean.URLs;
import com.taoyige.common.AlipaySignUtils;
import com.taoyige.common.BitmapUtil;
import com.taoyige.common.CalendarUtil;
import com.taoyige.common.NumberFormat;
import com.taoyige.common.UIHelper;
import com.taoyige.widget.LoadingDialog;

/**
 * 订单列表Adapter类
 * @author peter
 * @version 1.0
 * @created 2014-11-26
 */
public class ListOrdersAdapter extends BaseAdapter {
	private Context 					context;//运行上下文
	private List<Order> 					listItems;//数据集合
	private LayoutInflater 				listContainer;//视图容器
	private int 						itemViewResource;//自定义项视图源 
	private BitmapUtil bmpUtil;
	static class ListItemView{				//自定义控件集合  
			
			public TextView    order_id;
			public TextView    order_price;
			public TextView  	order_status;
		    public TextView  	order_time;
			public TextView    order_product_title;
			public ImageView    order_product_img;
			
			public Button  order_op1;
			public Button  order_op2;
			
			public RelativeLayout order_detail_rl;
	 }  

	/**
	 * 实例化Adapter
	 * @param context
	 * @param data
	 * @param resource
	 */
	public ListOrdersAdapter(Context context, List<Order> data,int resource) {
		this.context = context;			
		this.listContainer = LayoutInflater.from(context);	//创建视图容器并设置上下文
		this.itemViewResource = resource;
		this.listItems = data;
		this.bmpUtil = new BitmapUtil(BitmapFactory.decodeResource(context.getResources(), 0));
	}
	
	public int getCount() {
		return listItems.size();
	}

	public Object getItem(int arg0) {
		return null;
	}

	public long getItemId(int arg0) {
		return 0;
	}
	
	/**
	 * ListView Item设置
	 */
	public View getView(final int position,  View convertView, ViewGroup parent) {
		convertView = listContainer.inflate(this.itemViewResource, null);
		/* 节省内存但是动态隐藏按钮时存在bug
		ListItemView  listItemView = null;
		if (convertView == null) {
			convertView = listContainer.inflate(this.itemViewResource, null);
			listItemView = new ListItemView();
			order_id = (TextView)convertView.findViewById(R.id.nopay_order_id_value);
			order_price = (TextView)convertView.findViewById(R.id.nopay_order_money_value);
			order_status = (TextView)convertView.findViewById(R.id.nopay_order_orderstatus_value);
			order_product_title = (TextView)convertView.findViewById(R.id.nopay_order_title);
			order_product_img = (ImageView)convertView.findViewById(R.id.nopay_order_pic);
			order_time = (TextView)convertView.findViewById(R.id.nopay_order_ordertime_value);
			order_detail_rl=(RelativeLayout) convertView.findViewById(R.id.order_detail_rl);
			order_detail_rl.setOnClickListener(checkOrderDetailClickListener);
			convertView.setTag(listItemView);
		}else {
			listItemView = (ListItemView)convertView.getTag();
		}	*/
		 TextView order_id = (TextView)convertView.findViewById(R.id.nopay_order_id_value);
		 TextView order_price = (TextView)convertView.findViewById(R.id.nopay_order_money_value);
		 final TextView order_status = (TextView)convertView.findViewById(R.id.nopay_order_orderstatus_value);
		 TextView order_product_title = (TextView)convertView.findViewById(R.id.nopay_order_title);
		 ImageView order_product_img = (ImageView)convertView.findViewById(R.id.nopay_order_pic);
		 TextView order_time = (TextView)convertView.findViewById(R.id.nopay_order_ordertime_value);
		 RelativeLayout order_detail_rl=(RelativeLayout) convertView.findViewById(R.id.order_detail_rl);
		order_detail_rl.setOnClickListener(checkOrderDetailClickListener);
		final Order order = listItems.get(position);
		
		order_id.setText(order.getId());
		order_product_title.setText(order.getProduct().getTitle());
		order_product_title.setTag(order);//设置隐藏参数(实体类)
		order_price.setText(order.getTotalPrice()+"");
		order_time.setText(CalendarUtil.format(new Date(order.getTimestamp())));
		
		bmpUtil.loadBitmap(URLs.STATIC_HOST+order.getProduct().getThumbImageUrl().get(0),order_product_img);
		
		
		final Button order_op1 = (Button)convertView.findViewById(R.id.order_operation1);
		final Button order_op2 = (Button)convertView.findViewById(R.id.order_operation2);
		
		order_detail_rl.setTag(order);
		
		
		//根据订单的status设置按钮不同的值和隐藏按钮 TODO 
		
		order_op2.setTag(order);
		
		switch(order.getStatus()){
		case AppConfig.ORDER_UNPAID:
			order_status.setText(context.getString(R.string.orde_status_unpaid));
			order_op1.setTag(order);
			order_op1 .setOnClickListener(new CancelClickListener(position));
			
			new CountDownTimer((order.getTimer()-19*60*1000)-(order.getServerTime()-order.getTimestamp()),1000l) {
				@Override
				public void onTick(long millisUntilFinished) {
					if(millisUntilFinished/1000>60){
						long m=millisUntilFinished/(1000*60);
						long s=(millisUntilFinished%(1000*60))/1000;
						order_op2.setText(NumberFormat.format(m+"")+":"+NumberFormat.format(s+"")+" "+context.getString(R.string.orderpay));
					}else{
						long s=(millisUntilFinished%(1000*60))/1000;
						order_op2.setText("00:"+NumberFormat.format(s+"")+" "+context.getString(R.string.orderpay));
					}
					
				}
				@Override
				public void onFinish() {
					if(order!=null)
						cancelOrder(order,position,false);
					order_status.setText(context.getString(R.string.orde_status_closed));
					order_op1.setVisibility(View.INVISIBLE);
					order_op2.setVisibility(View.INVISIBLE);
					
				}
			}.start();

			
			order_op2 .setOnClickListener(new PayClickListener(position));
			break;
		case AppConfig.ORDER_PAID:
			order_status.setText(context.getString(R.string.orde_status_paid));
			order_op1.setVisibility(Button.INVISIBLE);
			order_op2.setText(context.getString(R.string.orde_refund));
			order_op2 .setOnClickListener(paidOrderClickListener);
			break;
			/** UNPAID(1),PAID(2),DELIVERED(3),CHECKED(4),CLOSED(5),DELETED(6),REFUND(7),REFUND_SUCCESS(8),RETURN_GOODS(9),RETURN_GOODS_SUCCESS(10);*/
		case AppConfig.ORDER_DELIVERED:
			order_status.setText(context.getString(R.string.orde_status_delivered));
			order_op1.setText(context.getString(R.string.orderstatusvalue));
			order_op2.setText(context.getString(R.string.orderok));
			order_op1.setTag(order);
			order_op1 .setOnClickListener(trackOrderClickListener);
			order_op2 .setOnClickListener(new RecepitClickListener(position));
			break;
		case AppConfig.ORDER_CHECKED:
			order_status.setText(context.getString(R.string.orde_status_checked));
			order_op2.setText(context.getString(R.string.orde_return_goods));
			order_op1.setVisibility(Button.INVISIBLE);
			order_op2 .setOnClickListener(returnGoodsOrderClickListener);
			break;
		case AppConfig.ORDER_CLOSED:
			order_status.setText(context.getString(R.string.orde_status_closed));
			order_op1.setVisibility(Button.INVISIBLE);
			order_op2.setVisibility(Button.INVISIBLE);
			break;
		case AppConfig.ORDER_DELETED:
			order_status.setText(context.getString(R.string.orde_status_deleted));
			order_op1.setVisibility(Button.INVISIBLE);
			order_op2.setVisibility(Button.INVISIBLE);
			break;
		case AppConfig.ORDER_REFUND:
			order_status.setText(context.getString(R.string.orde_status_refund));
			order_op1.setVisibility(Button.INVISIBLE);
			order_op2.setVisibility(Button.INVISIBLE);
			break;
		case AppConfig.ORDER_REFUND_SUCCESS:
			order_status.setText(context.getString(R.string.orde_status_refund_success));
			order_op1.setVisibility(Button.INVISIBLE);
			order_op2.setVisibility(Button.INVISIBLE);
			break;
		case AppConfig.ORDER_RETURN_GOODS:
			order_status.setText(context.getString(R.string.orde_status_return_goods));
			order_op1.setVisibility(Button.INVISIBLE);
			order_op2.setVisibility(Button.INVISIBLE);
			break;
		case AppConfig.ORDER_RETURN_GOODS_SUCCESS:
			order_status.setText(context.getString(R.string.orde_status_return_goods_scueess));
			order_op1.setVisibility(Button.INVISIBLE);
			order_op2.setVisibility(Button.INVISIBLE);
			break;
		}
		
		
		
		
		return convertView;
	}
	
	class CancelClickListener implements OnClickListener{

		private int position;
		public CancelClickListener(int position){
			this.position=position;
		}
		@Override
		public void onClick(final View v) {
			final Order o = (Order) v.getTag();

			AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
			builder.setIcon(android.R.drawable.ic_dialog_info);
			builder.setTitle(R.string.msg_order_cancel_title);
			builder.setMessage(R.string.msg_order_cancel_msg);
			builder.setPositiveButton(R.string.sure,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							cancelOrder(o,position,true);
						}
					});
			builder.setNegativeButton(R.string.cancle,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			builder.show();
			
		}
		
	}

	
	private View.OnClickListener paidOrderClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			UIHelper.ToastMessage(v.getContext(), v.getContext().getString(R.string.user_return_goods_refund));
		}
	};
	
	private View.OnClickListener trackOrderClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			Order o = (Order) v.getTag();
			UIHelper.showOrderTrack(v.getContext(), o.getId(),o.getUserID());
		}
	};
	
	class RecepitClickListener implements OnClickListener{

		private int position;
		public RecepitClickListener(int position){
			this.position=position;
		}
		@Override
		public void onClick(final View v) {
			final Order o = (Order) v.getTag();

			AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
			builder.setIcon(android.R.drawable.ic_dialog_info);
			builder.setTitle(R.string.msg_order_recepit_title);
			builder.setMessage(R.string.msg_order_recepit_msg);
			builder.setPositiveButton(R.string.sure,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							final  LoadingDialog loading = new LoadingDialog(context);
							final Handler handler = new Handler() {
								public void handleMessage(Message msg) {
									if (loading != null)
										loading.dismiss();
									if (msg.what == 1 ) {
										if(msg.obj!=null){
											Order od=(Order) msg.obj;
											if(od.getResult().getErrorCode()==200){
												removeItem(position);
												UIHelper.ToastMessage(context, "已经确认收货");
											}else{
												UIHelper.ToastMessage(context, "确认收货失败，请重试!");
											}
												
										}else{
											((AppException) msg.obj).makeToast(context);
										}
									} else{
										UIHelper.ToastMessage(context, context.getString(R.string.app_run_code_error));
									}
									
								}
							};
							loading.show();
							
							new Thread() {
								public void run() {
									Message msg = new Message();
									try {
										Order  order= ((AppContext)context.getApplicationContext()).orderRecepit(o.getId(), o.getUserID());
										if(order!=null&&order.getResult().getErrorCode()==200){
											msg.what = 1;
											msg.obj = order;
										}else{
											msg.what = -1;
											msg.obj = null;
										}

									} catch (AppException e) {
										e.printStackTrace();
										msg.what = -1;
										msg.obj = e;
									}
									handler.sendMessage(msg);
								}
							}.start();
						}
					});
			builder.setNegativeButton(R.string.cancle,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			builder.show();
			
		}
			
	};
	
	
	
	class PayClickListener implements OnClickListener{

		private int position;
		public PayClickListener(int position){
			this.position=position;
		}
		@Override
		public void onClick(final View v) {
			Order order = (Order) v.getTag();
			//UIHelper.showBuyNow(v.getContext(), o);
			//判断订单是否有效
			if(order==null){
				UIHelper.ToastMessage(context, R.string.msg_order_invalidate);
				return;
			}
			//一分钟的缓冲时间
			if(order.getServerTime()>order.getTimestamp()+order.getTimer()-60*1000){
				UIHelper.ToastMessage(context, R.string.msg_order_invalidate);
				return;
			}
			
			orderPay(v,order,position);
			
		}
			
	};
	
	
	
	private void orderPay(final View v,final Order o,final int position) {
		final Handler orderHandler = new Handler() {
			public void handleMessage(Message msg) {
				if (msg.what == 1 ) {
					if(msg.obj!=null){
						final Map<String, Object> map=(Map<String, Object>) msg.obj;
						AlipayResult resultObj = new AlipayResult((String) map.get("result"));
						String resultStatus = resultObj.getResultStatus();
						if (TextUtils.equals(resultStatus, "9000")) {
							//UIHelper.ToastMessage(BuyNowActivity.this, getString(R.string.pay_success));
							//更新订单
							//Order oo=appContext.orderPaid(orderId);
							new Thread() {
								public void run() {
									Message msg = new Message();
									try {
										String orderId=(String) map.get("orderId");
										Order oo=((AppContext)context.getApplicationContext()).orderPaid(orderId);
										msg.what = 1;
										msg.obj = oo;
									} catch (AppException e) {
										e.printStackTrace();
										msg.what = -1;
										msg.obj = e;
									}
								}
							}.start();
							removeItem(position);
							UIHelper.showUserCenter(context,AppConfig.BADGE_ORDER_PAID);
						} else {
							if (TextUtils.equals(resultStatus, "8000")) {
								UIHelper.ToastMessage(context, context.getString(R.string.pay_ing));
							} else if(TextUtils.equals(resultStatus, "6001")){
								UIHelper.ToastMessage(context, context.getString(R.string.pay_cancel));
							}else{
								UIHelper.ToastMessage(context, context.getString(R.string.pay_failed));
							}
						}
						
					}else{
						((AppException) msg.obj).makeToast(context);
					}
				} else{
					UIHelper.ToastMessage(context, context.getString(R.string.app_run_code_error));
				}
				
			}
		};
		new Thread() {
			public void run() {
				Message msg = new Message();
					if(o!=null&&o.getId()!=null){
						String alipayOrderInfo= ((AppContext)context.getApplicationContext()).getAlipayOrderInfo(o);
						String sign =  ((AppContext)context.getApplicationContext()).sign(alipayOrderInfo);
						
						try {
							sign = URLEncoder.encode(sign, "UTF-8");
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}
						final String payInfo = alipayOrderInfo + "&sign=\"" + sign + "\"&"+AlipaySignUtils.getSignType();
						
						PayTask alipay = new PayTask((Activity)v.getContext());
						String result = alipay.pay(payInfo);
						Map<String, Object> map=new HashMap<String, Object>();
						map.put("result", result);
						map.put("orderId", o.getId());
						msg.obj = map;
						msg.what = 1;
					}else{
						msg.obj = null;
						msg.what = -1;
					}
				orderHandler.sendMessage(msg);
			}
		}.start();
	}
	
	
	private void cancelOrder(final Order o,final int position,final boolean flag){
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				if (msg.what == 1 ) {
					if(msg.obj!=null){
						Order od=(Order) msg.obj;
						if(od.getResult().getErrorCode()==200){
							//更新数据
							if(flag)
								removeItem(position);
							UIHelper.ToastMessage(context, "已经取消该订单");
						}else{
							UIHelper.ToastMessage(context, "取消订单失败，请重试!");
						}
							
					}else{
						((AppException) msg.obj).makeToast(context);
					}
				} else if(msg.what==0){
					//Order od=(Order) msg.obj;
					//UIHelper.ToastMessage(context, od.getResult().getErrorMessage());
				}else if(msg.what==-1){
					UIHelper.ToastMessage(context, context.getString(R.string.app_run_code_error));
				}
				
			}
		};
		new Thread() {
			public void run() {
				Message msg = new Message();
				try {
					Order  order= ((AppContext)context.getApplicationContext()).orderCancel(o.getId(), o.getUserID());
					if(order!=null&&order.getResult().getErrorCode()==200){
						msg.what = 1;
						msg.obj = order;
					}else{
						msg.what = 0;
						msg.obj = order;
					}
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				handler.sendMessage(msg);
			}
		}.start();
	}
	
	
	private View.OnClickListener returnGoodsOrderClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			UIHelper.ToastMessage(v.getContext(), v.getContext().getString(R.string.user_return_goods_refund));
		}
	};
	
	private View.OnClickListener checkOrderDetailClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			Order o = (Order) v.getTag();
			UIHelper.showOrderDetail(v.getContext(), o.getId(),o.getUserID());
		}
	};
	
	  private void removeItem(int position){
		  if(listItems.size()>0&&listItems.size()>position)
		  		listItems.remove(position);
	        this.notifyDataSetChanged();
	    }
	  
	  private void refreshItem(){
	        this.notifyDataSetChanged();
	    }
	  
}